package com.evan.review.thread;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

import com.evan.review.R;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 专门演示线程池参数的Activity
 * 包含核心线程数、最大线程数、队列类型和大小、拒绝策略等参数的可视化演示
 */
public class ThreadPoolParamsActivity extends AppCompatActivity {
    private static final String TAG = "ThreadPoolParams";

    // UI组件
    private TextView tvCorePoolSize;
    private TextView tvMaxPoolSize;
    private TextView tvQueueType;
    private TextView tvQueueSize;
    private TextView tvRejectionPolicy;
    private SeekBar seekBarCoreSize;
    private SeekBar seekBarMaxSize;
    private RadioGroup rgQueueType;
    private SeekBar seekBarQueueSize;
    private RadioGroup rgRejectionPolicy;
    private Button btnSubmitTasks;
    private Button btnReset;
    private TextView tvLog;
    private NestedScrollView scrollLog;

    // 线程池配置参数
    private int corePoolSize = 2;
    private int maximumPoolSize = 4;
    private String queueType = "ArrayBlockingQueue"; // 默认队列类型
    private int queueSize = 3;
    private String rejectionPolicy = "AbortPolicy"; // 默认拒绝策略

    // 线程池对象
    private ThreadPoolExecutor threadPool;

    // 日志输出Handler
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    // 任务计数器
    private final AtomicInteger taskCounter = new AtomicInteger(0);

    // 任务执行时间 (模拟耗时)
    private static final long TASK_DURATION = 3000; // 3秒

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread_pool_params);

        initViews();
        setupListeners();
        updateThreadPoolInfo();
    }

    private void initViews() {
        tvCorePoolSize = findViewById(R.id.tv_core_pool_size);
        tvMaxPoolSize = findViewById(R.id.tv_max_pool_size);
        tvQueueType = findViewById(R.id.tv_queue_type);
        tvQueueSize = findViewById(R.id.tv_queue_size);
        tvRejectionPolicy = findViewById(R.id.tv_rejection_policy);

        seekBarCoreSize = findViewById(R.id.seekbar_core_size);
        seekBarMaxSize = findViewById(R.id.seekbar_max_size);
        rgQueueType = findViewById(R.id.rg_queue_type);
        seekBarQueueSize = findViewById(R.id.seekbar_queue_size);
        rgRejectionPolicy = findViewById(R.id.rg_rejection_policy);

        btnSubmitTasks = findViewById(R.id.btn_submit_tasks);
        btnReset = findViewById(R.id.btn_reset);
        tvLog = findViewById(R.id.tv_log);
        scrollLog = findViewById(R.id.scroll_log);

        // 设置初始值
        seekBarCoreSize.setProgress(corePoolSize);
        seekBarMaxSize.setProgress(maximumPoolSize);
        seekBarQueueSize.setProgress(queueSize);
    }

    private void setupListeners() {
        // 核心线程数调节
        seekBarCoreSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                corePoolSize = Math.max(1, progress); // 最小为1
                // 确保核心线程数不大于最大线程数
                if (corePoolSize > maximumPoolSize) {
                    maximumPoolSize = corePoolSize;
                    seekBarMaxSize.setProgress(maximumPoolSize);
                }
                updateThreadPoolInfo();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // 最大线程数调节
        seekBarMaxSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                maximumPoolSize = Math.max(corePoolSize, progress); // 确保不小于核心线程数
                updateThreadPoolInfo();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // 队列类型选择
        rgQueueType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_array_queue) {
                queueType = "ArrayBlockingQueue";
                seekBarQueueSize.setEnabled(true);
            } else if (checkedId == R.id.rb_linked_queue) {
                queueType = "LinkedBlockingQueue";
                seekBarQueueSize.setEnabled(true);
            } else if (checkedId == R.id.rb_sync_queue) {
                queueType = "SynchronousQueue";
                seekBarQueueSize.setEnabled(false); // 同步队列没有大小
            }
            updateThreadPoolInfo();
        });

        // 队列大小调节
        seekBarQueueSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                queueSize = Math.max(1, progress); // 最小为1
                updateThreadPoolInfo();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // 拒绝策略选择
        rgRejectionPolicy.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_abort_policy) {
                rejectionPolicy = "AbortPolicy";
            } else if (checkedId == R.id.rb_caller_runs_policy) {
                rejectionPolicy = "CallerRunsPolicy";
            } else if (checkedId == R.id.rb_discard_policy) {
                rejectionPolicy = "DiscardPolicy";
            } else if (checkedId == R.id.rb_discard_oldest_policy) {
                rejectionPolicy = "DiscardOldestPolicy";
            }
            updateThreadPoolInfo();
        });

        // 提交任务按钮
        btnSubmitTasks.setOnClickListener(v -> {
            addLog("开始提交任务...");
            createThreadPool();
            submitTasks();
        });

        // 重置按钮
        btnReset.setOnClickListener(v -> {
            shutdownThreadPool();
            clearLog();
            addLog("所有设置已重置，线程池已关闭");
        });
    }

    // 更新线程池信息显示
    private void updateThreadPoolInfo() {
        tvCorePoolSize.setText("核心线程数: " + corePoolSize);
        tvMaxPoolSize.setText("最大线程数: " + maximumPoolSize);

        // 队列类型显示
        String queueTypeText = "队列类型: ";
        switch (queueType) {
            case "ArrayBlockingQueue":
                queueTypeText += "数组阻塞队列 (有界)";
                break;
            case "LinkedBlockingQueue":
                queueTypeText += "链表阻塞队列 (有界)";
                break;
            case "SynchronousQueue":
                queueTypeText += "同步队列 (无存储)";
                break;
        }
        tvQueueType.setText(queueTypeText);

        // 队列大小显示
        if (queueType.equals("SynchronousQueue")) {
            tvQueueSize.setText("队列大小: 不适用 (直接传递任务)");
        } else {
            tvQueueSize.setText("队列大小: " + queueSize);
        }

        // 拒绝策略显示
        String rejectionText = "拒绝策略: ";
        switch (rejectionPolicy) {
            case "AbortPolicy":
                rejectionText += "终止策略 (抛出异常)";
                break;
            case "CallerRunsPolicy":
                rejectionText += "调用者运行策略 (在调用线程执行)";
                break;
            case "DiscardPolicy":
                rejectionText += "丢弃策略 (忽略任务)";
                break;
            case "DiscardOldestPolicy":
                rejectionText += "丢弃最旧策略 (丢弃最早的任务)";
                break;
        }
        tvRejectionPolicy.setText(rejectionText);
    }

    // 创建线程池
    private void createThreadPool() {
        // 如果已存在线程池，先关闭
        shutdownThreadPool();

        // 创建工作队列
        Object workQueue;
        switch (queueType) {
            case "ArrayBlockingQueue":
                workQueue = new ArrayBlockingQueue<Runnable>(queueSize);
                break;
            case "LinkedBlockingQueue":
                workQueue = new LinkedBlockingQueue<Runnable>(queueSize);
                break;
            case "SynchronousQueue":
            default:
                workQueue = new SynchronousQueue<Runnable>();
                break;
        }

        // 创建拒绝策略处理器
        RejectedExecutionHandler rejectedHandler;
        switch (rejectionPolicy) {
            case "CallerRunsPolicy":
                rejectedHandler = new ThreadPoolExecutor.CallerRunsPolicy();
                break;
            case "DiscardPolicy":
                rejectedHandler = new ThreadPoolExecutor.DiscardPolicy();
                break;
            case "DiscardOldestPolicy":
                rejectedHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
                break;
            case "AbortPolicy":
            default:
                rejectedHandler = new ThreadPoolExecutor.AbortPolicy();
                break;
        }

        // 创建线程池并捕获异常
        try {
            threadPool = new ThreadPoolExecutor(
                    corePoolSize,                     // 核心线程数
                    maximumPoolSize,                  // 最大线程数
                    60L,                              // 非核心线程存活时间
                    TimeUnit.SECONDS,                 // 时间单位
                    (BlockingQueue<Runnable>) workQueue,  // 工作队列
                    new NamedThreadFactory("演示线程-"),   // 线程工厂
                    rejectedHandler                   // 拒绝策略
            );

            addLog("线程池已创建 - 核心线程数: " + corePoolSize +
                    ", 最大线程数: " + maximumPoolSize +
                    ", 队列类型: " + queueType +
                    ", 队列大小: " + (queueType.equals("SynchronousQueue") ? "N/A" : queueSize) +
                    ", 拒绝策略: " + rejectionPolicy);
        } catch (Exception e) {
            addLog("线程池创建失败: " + e.getMessage());
        }
    }

    // 提交任务到线程池
    private void submitTasks() {
        if (threadPool == null || threadPool.isShutdown()) {
            addLog("线程池未创建或已关闭");
            return;
        }

        // 重置任务计数器
        taskCounter.set(0);

        // 模拟提交多个任务来演示线程池工作原理
        int totalTasks = corePoolSize + maximumPoolSize + queueSize + 2; // 确保有足够的任务触发各种情况

        for (int i = 1; i <= totalTasks; i++) {
            final int taskId = i;

            try {
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        String threadName = Thread.currentThread().getName();

                        // 提交任务日志
                        addLog("任务-" + taskId + " 已提交，由线程 [" + threadName + "] 执行");

                        try {
                            // 记录当前线程池状态
                            logPoolState();

                            // 模拟任务执行
                            Thread.sleep(TASK_DURATION);

                            // 任务完成
                            addLog("任务-" + taskId + " 已完成，线程 [" + threadName + "] 执行结束");

                            // 记录完成后的线程池状态
                            logPoolState();
                        } catch (InterruptedException e) {
                            addLog("任务-" + taskId + " 被中断");
                        }
                    }
                });

                // 记录任务提交信息
                addLog("提交任务-" + taskId + " 到线程池");

                // 每次提交后记录线程池状态
                logPoolState();

                // 短暂延迟以便观察效果
                Thread.sleep(500);

            } catch (Exception e) {
                addLog("任务-" + taskId + " 提交失败: " + e.getMessage());
            }
        }
    }

    // 记录线程池状态
    private void logPoolState() {
        if (threadPool == null) return;

        mainHandler.post(() -> {
            try {
                StringBuilder state = new StringBuilder("线程池状态: ");
                state.append("活跃线程=").append(threadPool.getActiveCount())
                        .append(", 当前线程数=").append(threadPool.getPoolSize())
                        .append(", 最大线程数=").append(threadPool.getMaximumPoolSize())
                        .append(", 核心线程数=").append(threadPool.getCorePoolSize())
                        .append(", 队列任务数=").append(threadPool.getQueue().size())
                        .append(", 已完成任务=").append(threadPool.getCompletedTaskCount());

                addLog(state.toString());
            } catch (Exception e) {
                Log.e(TAG, "Error logging pool state", e);
            }
        });
    }

    // 关闭线程池
    private void shutdownThreadPool() {
        if (threadPool != null && !threadPool.isShutdown()) {
            threadPool.shutdownNow();
            addLog("线程池已关闭");
        }
    }

    // 添加日志
    private void addLog(final String message) {
        mainHandler.post(() -> {
            tvLog.append(message + "\n\n");
            // 自动滚动到底部
            scrollLog.post(() -> scrollLog.fullScroll(View.FOCUS_DOWN));
        });
    }

    // 清空日志
    private void clearLog() {
        mainHandler.post(() -> {
            tvLog.setText("");
        });
    }

    // 自定义命名线程工厂
    private static class NamedThreadFactory implements java.util.concurrent.ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        public NamedThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            // 设置为非守护线程
            thread.setDaemon(false);
            // 设置普通优先级
            thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shutdownThreadPool();
    }
} 